package org.example.day04;

/**
 * ★第二章节2.2.3:用同步代码块解决同步方法的弊端
 */
public class MyThread3 {
    //成员变量
    private String getData1;
    private String getData2;
    public void LongTask(){
        try {
            System.out.println("begin task");
            Thread.sleep(3000);
            //局部变量
            String s1 = "值1  threadName = " + Thread.currentThread().getName();
            String s2 = "值2  threadName = " + Thread.currentThread().getName();
            //局部变量不存在同步问题.成员变量会因为多线程产生同步问题.
            //使用同步代码块，减小互斥区的范围，提高效率
            synchronized (this){
                getData1 = s1;
                getData2 = s2;
            }
            System.out.println(getData1);
            System.out.println(getData2);
            System.out.println("end task");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread3 m3 = new MyThread3();
        Thread3A ta = new Thread3A(m3);
        ta.start();
        Thread3B tb = new Thread3B(m3);
        tb.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long beginTime = CommonUtils.beginTime1;
        if(CommonUtils.beginTime2 < CommonUtils.beginTime1){
            beginTime = CommonUtils.beginTime2;
        }
        long endTime = CommonUtils.endTime1;
        if(CommonUtils.endTime2 > CommonUtils.endTime1){
            endTime = CommonUtils.endTime2;
        }
        System.out.println("耗时： " + ((endTime - beginTime) /1000));
    }
}

class CommonUtils1 {
    public static long beginTime1;
    public static long endTime1;
    public static long beginTime2;
    public static long endTime2;
}

class Thread3A extends Thread{
    private MyThread3 m3;
    public Thread3A(MyThread3 m3) {
        this.m3 = m3;
    }
    @Override
    public void run() {
        CommonUtils.beginTime1 = System.currentTimeMillis();
        m3.LongTask();
        CommonUtils.endTime1 = System.currentTimeMillis();
    }
}
class Thread3B extends Thread {
    private MyThread3 m3;
    public Thread3B(MyThread3 m3) {
        this.m3 = m3;
    }
    @Override
    public void run() {
        CommonUtils.beginTime2 = System.currentTimeMillis();
        m3.LongTask();
        CommonUtils.endTime2 = System.currentTimeMillis();
    }
}